<template>
  <!---搜索表单-->
    <div class="search-div">
        <el-form label-width="70px" size="small">
            <el-row>
                <el-col :span="6">
                    <el-form-item label="所属学院">
                        <el-select v-model="queryDto.collegeId" style="width: 100%" placeholder="请选择学院" filterable>
                            <el-option v-for="item in collegeList" :key="item.id" :label="item.name" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="专业名称">
                        <el-input v-model="queryDto.majorName" style="width: 100%"
                                  placeholder="请输入专业名称"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row style="display:flex">
                <el-button type="primary" size="small" @click="searchMajor"> 搜索</el-button>
                <el-button size="small" @click="resetData">重置</el-button>
            </el-row>
        </el-form>
    </div>

  <!--添加按钮-->
    <div class="tools-div">
        <el-button type="success" size="small" @click="addShow">添 加</el-button>
    </div>

    <el-dialog v-model="dialogVisible" title="添加或修改" width="40%" @close="handleDialogClose">
        <el-form label-width="120px">
            <el-form-item label="专业名称">
                <el-input v-model="major.name"/>
            </el-form-item>
            <el-form-item label="专业代码">
                <el-input v-model="major.code" :disabled="disabled"/>
            </el-form-item>
            <el-form-item label="所属学院">
                <el-select v-model="major.collegeId" style="width: 100%" placeholder="请选择学院" filterable>
                    <el-option v-for="item in collegeList" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submit">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

  <!-- 分配课程的弹窗 -->
    <el-dialog v-model="dialogVisibleCourse" title="分配课程" width="50%" @close="handleDialogCloseCourse">
        <el-tabs v-model="activeName">
            <el-tab-pane label="本学院" name="first">
                <!-- 添加课程筛选 -->
                <el-form>
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item label="课程类别">
                                <el-select v-model="queryCourseDto.category" style="width: 100%"
                                           placeholder="请选择类别" filterable>
                                    <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name"
                                               :value="item.id"/>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="课程性质">
                                <el-select v-model="queryCourseDto.nature" style="width: 100%" placeholder="请选择"
                                           filterable>
                                    <el-option v-for="item in natureOptions" :key="item.id" :label="item.name"
                                               :value="item.id"/>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item>
                                <el-button type="primary" @click="handleFilter">筛选</el-button>
                                <el-button type="info" @click="resetCourseData">重置</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <el-scrollbar max-height="450px">
                    <el-checkbox-group v-model="selectedCourses" class="course-group">
                        <el-checkbox v-for="course in localCourses" :label="course.id"
                                     :key="course.id">{{ course.name }}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-scrollbar>
            </el-tab-pane>
            <el-tab-pane label="其他学院" name="second">
                <el-row>
                    <!-- 左侧学院列表 -->
                    <el-col :span="9">
                        <el-scrollbar max-height="500px">
                            <el-menu :default-active="selectedCollegeId" :text-color="'#676464'" class="custom-menu"
                                     :active-text-color="'#4e85f6'" @select="handleCollegeSelect">
                                <el-menu-item v-for="college in otherColleges" :key="college.id" :index="college.id">
                                    {{ college.name }}
                                </el-menu-item>
                            </el-menu>
                        </el-scrollbar>
                    </el-col>
                    <!-- 右侧课程列表 -->
                    <el-col :span="15">
                        <el-scrollbar max-height="400px">
                            <el-checkbox-group style="margin-left: 10px" v-model="selectedCourses" class="course-group">
                                <el-checkbox v-for="course in otherCourses" :label="course.id" :key="course.id">
                                    {{ course.name }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-scrollbar>
                    </el-col>
                </el-row>
            </el-tab-pane>
        </el-tabs>
        <div class="dialog-footer">
            <el-button type="warning" @click="checkboxEmits">检查已选课程</el-button>
            <el-button type="primary" @click="handleAssign">确定</el-button>
            <el-button @click="dialogVisibleCourse = false">取消</el-button>
        </div>
    </el-dialog>
  <!-- 选中的所有课程 -->
    <el-drawer v-model="drawer" :title="`已选课程（${selectedCoursesList.length}门）`" size="20%">
        <div style="overflow: auto">
            <el-card v-for="course in selectedCoursesList" :key="course" style="margin-bottom: 5px;">
                <el-row :gutter="24">
                    <el-col :span="20">
                        <span>{{ course.name }}</span>
                    </el-col>
                    <el-col :span="4">
                        <el-button size="small" type="danger" @click="removeCourse(course)" :icon="Delete" circle/>
                    </el-col>
                </el-row>
            </el-card>
        </div>
    </el-drawer>

    <el-dialog title="专业课程列表" v-model="dialogVisibleCourseList" width="50%"
               @close="dialogVisibleCourseList=false">
        <el-table :data="courseList" border style="max-height: 400px;overflow: auto">
            <el-table-column prop="courseName" label="课程名称" min-width="400px"/>
            <el-table-column prop="academicYear" label="学年" #default="scope" min-width="90px">
                {{ yearOptions[scope.row.academicYear] }}
            </el-table-column>
            <el-table-column prop="semester" label="学期" #default="scope" min-width="90px">
                <el-tag v-if="scope.row.semester" :type="scope.row.semester == 1?'danger':'success'">{{
                    semesterOptions[scope.row.semester]
                    }}
                </el-tag>
            </el-table-column>
            <el-table-column label="操作" #default="scope" width="75px">
                <el-button type="primary" size="small" @click="EditAcademic(scope.row)">设置</el-button>
            </el-table-column>
        </el-table>
    </el-dialog>
    <el-dialog title="专业课程设置" v-model="dialogVisibleCourseSet" width="20%"
               @close="dialogVisibleCourseSet=false">
        <el-form :model="courseSetForm" label-width="40px">
            <el-form-item label="学年">
                <el-select v-model="courseSetForm.academicYear" placeholder="请选择学年">
                    <el-option v-for="(label, value) in yearOptions" :key="value" :label="label" :value="value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="学期">
                <el-select v-model="courseSetForm.semester" placeholder="请选择学期">
                    <el-option v-for="(label, value) in semesterOptions" :key="label" :label="label" :value="value"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleAcadmicYear">确定</el-button>
                <el-button @click="dialogVisibleCourseSet = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

  <!---数据表格-->
    <el-table :data="list" style="width: 100%" border>
        <el-table-column prop="id" label="序号" width="60px" align="center"/>
        <el-table-column prop="name" label="专业名称" width="300px"/>
        <el-table-column prop="code" label="专业代码" width="100px"/>
        <el-table-column prop="collegeName" label="所属学院"/>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column prop="updateTime" label="更新时间"/>
        <el-table-column label="操作" align="center" #default="scope" fixed="right" width="300px">
            <el-button type="warning" size="small" @click="assignCourse(scope.row)">分配课程</el-button>
            <el-button type="success" size="small" @click="showMajorDetail(scope.row)">查看课程</el-button>
            <el-button type="primary" size="small" @click="editMajor(scope.row)"> 修改</el-button>
            <el-button type="danger" size="small" @click="deleteById(scope.row)"> 删除</el-button>
        </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="pageParams.page" v-model:page-size="pageParams.limit"
                   :page-sizes="[5, 10, 20, 50, 100]" @size-change="fetchData" @current-change="fetchData"
                   layout="total, sizes, prev, pager, next" :total="total"/>
</template>

<!-- script部分修改内容 -->
<script setup>
import {Delete} from '@element-plus/icons-vue'
import {onMounted, ref, watch} from 'vue'
import {
    DeleteMajorById,
    DoAssignCourse,
    GetCheckCollege,
    GetCourseByMajoeId,
    GetMajorListByPage,
    SaveMajor,
    UpdateCourseMajor,
    UpdateMajor
} from '@/api/major'
import {ElMessage, ElMessageBox} from 'element-plus'
import {GetAllCollege} from "@/api/college";
import {FetchLocalCoursesByCollegeId, FindAllCategory, FindAllNature, GetCourseById} from "@/api/course";

const disabled = ref(false)
const dialogVisibleCourse = ref(false)
const activeName = ref('first');
const categoryOptions = ref([])
const natureOptions = ref([])
const collegeId = ref(null)
const drawer = ref(false)
const fetchCategoryList = async () => {
    const {data} = await FindAllCategory()
    categoryOptions.value = data
}
const fetchNatureList = async () => {
    const {data} = await FindAllNature()
    natureOptions.value = data
}
const queryCourseDto = ref({
    category: null,
    nature: null
})

// 重置按钮点击事件处理函数
const resetCourseData = async () => {
    queryCourseDto.value = {}
    await fetchCourseData(collegeId.value)
}

//查看课程详情
const yearOptions = {
    1: '第一学年',
    2: '第二学年',
    3: '第三学年',
    4: '第四学年'
};
const semesterOptions = {
    1: '秋季学期',
    2: '春季学期'
};
const courseList = ref([])
const courseSetForm = ref({
    id: '',
    majorId: '',
    courseId: '',
    academicYear: '',
    semester: ''
})
const dialogVisibleCourseList = ref(false)
const dialogVisibleCourseSet = ref(false)
//设置学年学期
const EditAcademic = async (row) => {
    dialogVisibleCourseSet.value = true
    courseSetForm.value = row
}
//提交学年学期
const handleAcadmicYear = async () => {
    const {code} = await UpdateCourseMajor(courseSetForm.value)
    if (code === 200) {
        ElMessage.success('设置成功')
    }
    dialogVisibleCourseSet.value = false
}
const showMajorDetail = async (row) => {
    dialogVisibleCourseList.value = true
    const {data} = await GetCourseByMajoeId(row.id)
    courseList.value = data
}

//根据学院查询所有课程
const fetchCourseData = async (collegeId) => {
    const {data} = await FetchLocalCoursesByCollegeId(collegeId, queryCourseDto.value.category, queryCourseDto.value.nature)
    localCourses.value = data
}

const selectedCollegeId = ref() //其他学院默认选中的学院id
const localCourses = ref([]) // 本学院课程列表
const otherColleges = ref([])// 其他学院列表
const otherCourses = ref([]) // 其他学院课程列表

const selectedCourses = ref([])  //选中的课程id集合
const selectedCoursesList = ref({
    id: '',
    name: ''
}); // 存储选中的课程信息

const allCourses = ref([]);//所有的课程信息

// 监听 otherCourses 数组的变化，并更新 allCourses
watch(otherCourses, () => {
    allCourses.value = [...localCourses.value, ...otherCourses.value];
});

// 处理分配课程操作
const checkboxEmits = async () => {
    if (selectedCourses.value.length === 0) {
        ElMessage.warning('抱歉，您还没有选择课程')
        return
    }
    drawer.value = true
    // 将选中的课程信息添加到已选课程列表中
    const {data} = await GetCourseById(selectedCourses.value)
    selectedCoursesList.value = data
}

//确定分配
const handleAssign = async () => {
    if (selectedCourses.value.length === 0) {
        ElMessage.warning('请选择要分配的课程')
        return
    }
    const {code} = await DoAssignCourse(majorId.value, selectedCourses.value)
    if (code === 200) {
        ElMessage.success('分配课程成功')
    }
    handleDialogCloseCourse()
}


// 点击标签关闭按钮时触发的方法
const removeCourse = (course) => {
    const index = selectedCoursesList.value.indexOf(course)
    if (index !== -1) {
        selectedCoursesList.value.splice(index, 1)
        // 删除课程后，需要手动触发视图更新
        selectedCoursesList.value = [...selectedCoursesList.value]
        // 同时取消对应的 checkbox 勾选
        const checkboxIndex = selectedCourses.value.indexOf(course.id)
        if (checkboxIndex !== -1) {
            selectedCourses.value.splice(checkboxIndex, 1)
        }
    }
}

const majorId = ref() // 初始化为 null 或其他初始值
//分配课程
const assignCourse = async row => {
    majorId.value = row.id
    collegeId.value = row.collegeId
    dialogVisibleCourse.value = true
    await fetchCategoryList()
    await fetchNatureList()
    await fetchCourseData(row.collegeId)
    const {data} = await GetCheckCollege(row.id)
    selectedCourses.value = data
    otherColleges.value = collegeList.value.filter(college => college.id !== row.collegeId)
    // 页面加载时立即查询第一个学院的课程表
    if (otherColleges.value.length > 0) {
        selectedCollegeId.value = otherColleges.value[0].id;
        await handleCollegeSelect(selectedCollegeId.value);
    }
}

//本学院筛选课程
const handleFilter = async () => {
    await fetchCourseData(collegeId.value)
}

//关闭分配课程
const handleDialogCloseCourse = () => {
    activeName.value = 'first'
    dialogVisibleCourse.value = false
    queryCourseDto.value = {}
    selectedCourses.value = []
}

// 处理选择其他学院后的变化
const handleCollegeSelect = async (outherCollegeId) => {
    const {data} = await FetchLocalCoursesByCollegeId(outherCollegeId)
    otherCourses.value = data
}


// 删除数据
const deleteById = row => {
    ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        const {code} = await DeleteMajorById(row.id)
        if (code === 200) {
            ElMessage.success('删除成功')
            pageParams.value.page = 1
            await fetchData()
        }
    })
}

// 修改按钮点击事件处理函数
const editMajor = row => {
    major.value = row
    dialogVisible.value = true
    disabled.value = true
}

//表单数据模型
const defaultForm = {
    name: '',
    code: '',
    collegeId: ''
}

const major = ref(defaultForm) // 使用ref包裹该对象，使用reactive不方便进行重置

const handleDialogClose = () => {
    major.value = {...defaultForm} // 重置数据为默认值
    dialogVisible.value = false
    disabled.value = false
}

// 添加专业
const submit = async () => {
    if (!major.value.id) {
        const {code} = await SaveMajor(major.value)
        if (code === 200) {
            dialogVisible.value = false
            ElMessage.success('操作成功')
            await fetchData()
        }
    } else {
        const {code} = await UpdateMajor(major.value)
        if (code === 200) {
            dialogVisible.value = false
            ElMessage.success('操作成功')
            await fetchData()
        }
    }
}

// 分页条总记录数
let total = ref(0)

// 定义表格数据模型
let list = ref([])

// 控制对话是否展示的变量
const dialogVisible = ref(false)

//进入添加
const addShow = () => {
    dialogVisible.value = true
}

//分页数据
const pageParamsForm = {
    page: 1, // 页码
    limit: 10, // 每页记录数
}

const pageParams = ref(pageParamsForm) // 将pageParamsForm包装成支持响应式的对象

// 搜索表单数据
const queryDto = ref({majorName: '', collegeId: ''})

const collegeList = ref([])

const getCollegeList = async () => {
    const {data} = await GetAllCollege()
    collegeList.value = data
}

// 页面加载完毕以后请求后端接口获取数据
onMounted(async () => {
    await fetchData()
    await getCollegeList()
})

// 搜索按钮点击事件处理函数
const searchMajor = () => {
    fetchData()
}

// 重置按钮点击事件处理函数
const resetData = () => {
    queryDto.value = {}
}

// 远程调用后端分页查询接口
const fetchData = async () => {
    const {data} = await GetMajorListByPage(
        pageParams.value.page,
        pageParams.value.limit,
        queryDto.value
    )
    list.value = data.list
    total.value = data.total
}
</script>

<style scoped>
.search-div {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}

.tools-div {
    margin: 10px 0;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}


.dialog-footer {
    padding: 10px 20px;
    text-align: center;
}

.course-group {
    margin-top: 15px;
}

.custom-menu .el-menu-item:hover {
    background-color: #ffffff; /* 鼠标悬停时的背景颜色 */
}


</style>
